import { defineStore } from 'pinia';
import router from '@/router';
import { useUserStore } from './user';
import { asyncRouter } from '@/router/modules';
import { filterRoutesByRole, filterRoutesToMenus } from '@/router/helpers';
import { getCurrentUserPermissionsApi } from '@/api/auth';

const viewsComponent: Record<string, any> = import.meta.glob('/src/views/**/*.vue', {
  eager: true
});

interface IRouteState {
  /** 权限路由的模式(static|dynamic) */
  routeMode: ImportMetaEnv['VITE_ROUTE_MODE'];
  /** 是否初始化权限路由的生成 */
  isInitRoute: boolean;
  /** 菜单渲染数据 */
  menus: App.Menu[];
  /** 缓存的路由 */
  cacheList: string[];
}
// interface RoleMenu {
//   _id: number;
//   affix: number;
//   name: string;
//   component: string;
//   createTime: string;
//   icon: string;
//   iframeLink: string;
//   isHide: number;
//   isKeep: number;
//   path: string;
//   permission: string;
//   pid: number;
//   sort: number;
//   title: string;
//   type: number;
//   updateTime: string;
//   __v: number;
//   children?: RoleMenu[];
// }
export const useRouteStore = defineStore({
  id: 'route',
  state: (): IRouteState => ({
    routeMode: import.meta.env.VITE_ROUTE_MODE,
    isInitRoute: false,
    menus: [],
    cacheList: []
  }),
  getters: {},
  actions: {
    /** 初始化权限路由 */
    initRoute() {
      if (this.routeMode === 'static') {
        this.initStaticRoute();
      } else {
        this.initDynamicRoute();
      }
    },
    /** 静态权限路由 */
    initStaticRoute() {
      const userStore = useUserStore();
      const routes = filterRoutesByRole(asyncRouter, userStore.userInfo.roleName);
      routes.forEach((route) => {
        route.children?.length ? router.addRoute(route) : router.addRoute('root', route);
      });
      const menus = filterRoutesToMenus(routes);
      this.setMenus(menus);
      this.isInitRoute = true;
    },
    /** 动态权限路由 */
    async initDynamicRoute() {
      // 请求位置需要更换 到App.vue
      const routes = await getCurrentUserPermissionsApi();
      //   const routes = [
      //     {
      //       id: 1,
      //       pid: 0,
      //       title: '首页',
      //       path: '/dashboard',
      //       component: '',
      //       icon: 'el-icon-odometer',
      //       hidden: 0,
      //       sort: 1,
      //       type: 0,
      //       children: [
      //         {
      //           id: 11,
      //           pid: 1,
      //           title: '分析页',
      //           path: '/dashboard/analysis',
      //           icon: 'el-icon-dataLine',
      //           component: '/dashboard/analysis/index',
      //           hidden: 0,
      //           sort: 0,
      //           type: 1
      //         },
      //         {
      //           id: 12,
      //           pid: 1,
      //           title: '工作台',
      //           path: '/dashboard/workbench',
      //           component: '/dashboard/workbench/index',
      //           icon: 'el-icon-monitor',
      //           hidden: 0,
      //           sort: 0,
      //           type: 1
      //         }
      //       ]
      //     },
      //     {
      //       id: 2,
      //       pid: 0,
      //       title: '系统管理',
      //       path: '/system',
      //       component: '',
      //       icon: 'el-icon-setting',
      //       hidden: 0,
      //       sort: 2,
      //       type: 0,
      //       children: [
      //         {
      //           id: 21,
      //           pid: 2,
      //           title: '菜单管理',
      //           path: '/system/menu',
      //           component: '/system/menu/index',
      //           icon: 'el-icon-more',
      //           hidden: 0,
      //           sort: 0,
      //           type: 1
      //         },
      //         {
      //           id: 22,
      //           pid: 2,
      //           title: '角色管理',
      //           path: '/system/role',
      //           component: '/system/role/index',
      //           icon: 'el-icon-more',
      //           hidden: 0,
      //           sort: 0,
      //           type: 1
      //         },
      //         {
      //           id: 23,
      //           pid: 2,
      //           title: '用户管理',
      //           path: '/system/user',
      //           component: '/system/user/index',
      //           icon: 'el-icon-more',
      //           hidden: 0,
      //           sort: 0,
      //           type: 1
      //         }
      //       ]
      //     }
      //   ];
      const addRouteAll = (menu: any) => {
        //RoleMenu就是接口返回的数据的类型
        menu.forEach((item: any) => {
          const componentkey = `/src/views${item.component}.vue`;
          const component = viewsComponent[componentkey];
          if (item.type === 0 || component) {
            // addRouteItem(item)
            item.name = item.path.substring(1);

            item.component = component ? component.default : '';
            item.meta = {
              title: item.title,
              icon: item.icon
            };
          }
          if (item.children && item.children.length > 0) {
            addRouteAll(item.children);
          }
        });
      };
      addRouteAll(routes);
      routes.data.forEach((route: any) => {
        route.children?.length ? router.addRoute(route) : router.addRoute('root', route);
      });
      const menus = filterRoutesToMenus(routes.data);
      this.setMenus(menus);
      this.isInitRoute = true;
    },
    /** 设置菜单 */
    setMenus(menus: App.Menu[]) {
      this.menus = menus;
    }
  }
});
